import { Button, Upload, message, Image } from 'antd';
import { UploadChangeParam, UploadFile, UploadProps } from 'antd/es/upload';
import { useState, useEffect } from 'react';

import { Iconify } from '@/components/icon';
import { beforeAvatarUpload } from '@/components/upload/utils';

// import { StyledUploadAvatar } from './styles';

const { VITE_APP_DOMAIN: DOMAIN } = import.meta.env;

interface Props extends UploadProps {
  defaultAvatar?: string;
  helperText?: React.ReactElement | string;
  onUploadSuccess?: (success: number[]) => void;
  title?: string;
  portraitList: number[]; // 添加 portraitList 属性
}

export function UploadPicture({ onUploadSuccess, disabled, portraitList, title, ...other }: Props) {
  const [imageUrl, setImageUrl] = useState<string[]>([]);
  const [isHover, setIsHover] = useState<boolean>(true);
  const [portraitListData, setPortraitListData] = useState<number[]>([]); // 添加 portraitList 属性
  const handelHover = (hover: boolean) => {
    setIsHover(hover);
  };
  useEffect(() => {
    if (portraitList[0]) {
      setPortraitListData(portraitList);
      setImageUrl(portraitList.map((id) => `${DOMAIN}/api/file/oss/${id}`));
    }
  }, []);
  const handleChange: UploadProps['onChange'] = async (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      message.success('上传成功！');
      const newImageUrl = [...imageUrl, `${DOMAIN}/api/file/oss/${info.file.response.success}`];
      setImageUrl(newImageUrl);
      setPortraitListData([...portraitListData, info.file.response.success]); // 传递 success 给父组件
    }
    if (info.file.status === 'error') {
      message.error('上传失败，请重试！');
    }
  };
  useEffect(() => {
    onUploadSuccess?.(portraitListData); // 传递 success 给父组件
  }, [portraitListData]);
  const renderPreview = (
    <Image.PreviewGroup
      items={imageUrl.map((url) => ({
        src: url,
      }))}
    >
      {imageUrl.map((url, index) => (
        <div key={index} style={{ position: 'relative', display: 'inline-block', margin: '5px' }}>
          <Image
            src={url}
            alt={`uploaded-${index}`}
            style={{ width: '100px', height: '100px', objectFit: 'cover' }}
          />
          <Button
            onClick={() => handleDelete(index)} // 点击删除按钮时调用 handleDelete
            style={{
              width: '20px',
              height: '20px',
              position: 'absolute',
              top: '5px',
              right: '5px',
              background: 'rgba(255, 255, 255, 0.7)',
              border: 'none',
              borderRadius: '50%',
              cursor: `${disabled ? '' : 'pointer'}`,
              padding: '0px',
              lineHeight: '16px',
              display: isHover ? 'block' : 'none', // 根据 isHover 控制显示
            }}
          >
            ×
          </Button>
        </div>
      ))}
    </Image.PreviewGroup>
  );

  // 添加 handleDelete 函数
  const handleDelete = (index: number) => {
    const newImageUrl = imageUrl.filter((_, i) => i !== index); // 过滤掉被删除的图片
    const newPortraitListData = portraitListData.filter((_, i) => i !== index);
    setImageUrl(newImageUrl); // 更新状态
    setPortraitListData(newPortraitListData);
  };

  const renderPlaceholder = (
    <div
      style={{
        backgroundColor: !imageUrl || isHover ? 'rgba(22, 28, 36, 0.64)' : 'transparent',
        color: '#fff',
        width: '100%',
        height: '100%',
      }}
      className="absolute z-10 flex h-full w-full flex-col items-center justify-center"
    >
      <Iconify icon="solar:camera-add-bold" size={32} />
      <div className="mt-1 text-xs">{title || '上传图片'}</div>
    </div>
  );

  const renderContent = (
    <div
      className="relative flex h-20 w-20  items-center justify-center overflow-hidden"
      // className="relative flex h-full w-full items-center justify-center overflow-hidden rounded-full"
      onMouseEnter={() => handelHover(true)}
      onMouseLeave={() => handelHover(true)}
    >
      {renderPlaceholder}
    </div>
  );

  return (
    <div style={{ display: 'flex', justifyContent: 'center' }}>
      {renderPreview}

      <Upload
        disabled={disabled}
        name="file"
        action="/api/file/oss/upload" // 添加上传接口地址，API
        showUploadList={false}
        listType="picture-card"
        {...other}
        beforeUpload={beforeAvatarUpload}
        onChange={handleChange}
      >
        {renderContent}
      </Upload>
    </div>
  );
}
